<template>
  <div class="detailWrapper h100">
    <!-- :stepConfig="stepConfig" -->
    <!-- :moreBtnArr="moreBtnArr" -->
    <!-- :showMore="pageType != 'add'" -->
    <editPageNew
      ref="editPage"
      :rightBtnArr="rightBtnArr"
      :creatInfo="formData"
      showTopTitle
    >
      <template slot="editPageTitle">
        <span class="title-code">工单知识 {{ formData.code || "" }}</span>
      </template>
      <!-- 标题 -->
      <!-- <div class="plan-title">
        <div v-show="!showInput" class="name">
          <span style="color: red"></span>
          <span>{{ titleName }}</span>
          <el-link
            v-show="titleEdit"
            style="font-size: 20px"
            icon="el-icon-edit-outline"
            @click="editTitle"
          ></el-link>
        </div>
        <div v-show="showInput" class="name-input">
          <el-input
            type="text"
            v-model="titleName"
            maxlength="64"
            show-word-limit
            @blur="loseFocus"
            @change="userInputTitle"
            placeholder="请输入名称"
            clearable
            ref="mark"
            ><template slot="prepend" style="color: red"
              >标题</template
            ></el-input
          >
        </div>
      </div> -->
      <el-collapse v-model="activeNames" style="padding-right: 10px">
        <el-collapse-item name="1">
          <template slot="title">
            <span class="titleLine"></span>
            基本信息
          </template>
          <editForm
            :formConfig="basicConfig"
            ref="basicForm"
            :formData="formData"
          >
          </editForm>
        </el-collapse-item>
      </el-collapse>
    </editPageNew>
  </div>
</template>

<script>
import {
  queryOrderAssetDetail,
  saveOrderAssetDetail,
  updateOrderAssetDetail,
  deleteOrderAssetDetail,
} from "@/api/standardManagement/orderAsset.js";
export default {
  data() {
    return {
      titleName: "",
      formData: {},
      activeNames: ["1"],
      basicConfig: {
        labelWidth: "140px",
        itemArr: [
          {
            label: "设备类型名称:",
            prop: "typeName",
            idsStr: "typeId",
            type: "deviceClassify",
            required: true,
            disabled: false,
            span: 8,
            methods: (data) => {
              // 生成标题
              this.producedTitle(data[0].name);
            },
          },
          {
            label: "缺陷关键字",
            prop: "keys", //多选时，字段要为数组类型
            //propArr: "keyArr",
            idsStr: "keysId",
            //option: [],
            type: "defectKeyWord", //类型
            trigger: "change",
            methods: (obj) => {
              this.selectKeys(obj);
            },
            required: true,
            disabled: false,
            span: 8,
          },
          {
            label: "处理方式",
            prop: "solution",
            type: "text",
            placeholder: "请输入",
            required: false,
            disabled: false,
            span: 8,
          },
          {
            label: "创建人",
            prop: "createByName", //多选时，字段要为数组类型
            propArr: "createByNameArr",
            idsStr: "createBy",
            multiple: false, //是否多选
            isOutOrg: 0, //是否是外单位
            allowCreate: true, //是否允许创建条目
            option: [], //当前选中的项
            type: "user-select", //类型
            trigger: "change",
            methods: (obj) => {},
            span: 8,
            disabled: false,
          },
          {
            label: "创建时间",
            prop: "createTime",
            type: "datetime",
            required: true,
            pickerOptions: {
              disabledDate(time) {
                return time.getTime() > Date.now();
              },
            },
            span: 8,
            disabled: false,
          },
          {
            label: "故障原因",
            prop: "errorCase",
            type: "textarea",
            maxlength: "100",
            required: true,
            span: 12,
            rows: 3,
            disabled: false,
          },
          {
            label: "故障描述",
            prop: "errorDesc",
            type: "textarea",
            maxlength: "100",
            required: true,
            span: 12,
            rows: 3,
            disabled: false,
          },
        ],
      },
      pageType: "",
    };
  },
  computed: {
    rightBtnArr() {
      return [
        {
          text: "保存",
          icon: "icon-a-wanchengbaocun",
          hide: ["detail"].includes(this.pageType),
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("save"),
          methods: () => {
            // 新建状态保存
            if (this.pageType == "add") {
              this.saveDetail();
              return;
            }
            // 编辑状态保存
            if (this.pageType == "edit") {
              this.updateDetail();
              return;
            }
          },
        },
        {
          text: "编辑",
          hide: ["add", "edit"].includes(this.pageType),
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("edit"),
          icon: "el-icon-edit",
          methods: () => {
            this.pageType = "edit";
            this.basicConfig.itemArr.map((i) => (i.disabled = false));
            // this.editDetail();
          },
        },
        {
          text: "取消",
          hide: ["add", "detail"].includes(this.pageType),
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("edit"),
          icon: "el-icon-edit",
          methods: () => {
            this.pageType = "detail";
            this.basicConfig.itemArr.map((i) => (i.disabled = true));
            // 重新请求变更前表单数据并覆盖formData
            this.getDetails(this.formData.id)
            // this.editDetail();
          },
        },
        {
          text: "删除",
          icon: "el-icon-delete-solid",
          hide: ["add", "edit"].includes(this.pageType),
          content: "未授权功能",
          disabled: !this.$store.getters.isBtnAuth("delete"),
          methods: () => {
            this.deleteDetail();
          },
        },
      ];
    },
  },
  methods: {
    init() {
      // 根据id判断是新建还是详情
      let { id, pageType } = this.$route.query;
      if (id) {
        debugger
        // 有id，说明是从列表点击进入详情页
        this.pageType = pageType || 'detail';
        this.basicConfig.itemArr.map((i) => (i.disabled = true));
        // this.basicConfig = this.handleEditConfig(this.basicConfig.itemArr, true)
        // this.titleEdit = false;
        this.getDetails(id);
      } else {
        this.pageType = "add";
        this.showInput = true;
        this.$set(
          this.formData,
          "appid",
          this.$store.state.user.userInfo.appId
        );
        this.$set(
          this.formData,
          "appName",
          this.$store.state.user.userInfo.appName
        );
      }
    },
    // 禁用/启用表单编辑
    // handleEditConfig(itemArr, flag) {
    //   if(itemArr && Array.isArray(itemArr)) {
    //     return itemArr.map((i) => (i.disabled = flag))
    //   }
    // },
    // 获取详情
    getDetails(id) {
      queryOrderAssetDetail({ id }).then((res) => {
        if (res.code == 200) {
          this.formData = res.data;
          // this.titleName = this.formData
          let { createBy, createByName } = this.formData;
          let option = this.$utils.getOptionData(createByName, createBy);
          this.formData.createByNameArr = createBy;
          setTimeout(() => {
            if (this.$refs.basicForm) {
              this.$refs.basicForm.setItemOption("createByName", option);
            }
          }, 200);
        }
      });
    },
    // 标题栏失焦
    loseFocus() {},
    // 标题栏内容变更
    userInputTitle() {},
    // 编辑标题栏
    editTitle() {},
    // 生成标题
    producedTitle() {},
    // 选择缺陷关键字
    selectKeys(data) {
      let { keyword, id, others } = data;
      let formData = this.$refs.basicForm.getCurrentData();
      this.$refs.basicForm.setFormItem("keys", keyword);
      this.currentKeys = keyword;
      this.$refs.basicForm.setFormItem("keysId", id);
      if (formData.desc == "") {
        this.$refs.basicForm.setFormItem("desc", others);
      }
    },
    // 保存
    async saveDetail() {
      try {
        let formData = await this.$refs.basicForm.getFormData();
        // if (this.titleName == "") {
        //   this.loseFocus();
        // } else {
        if (this.pageType == "add") {
          // 过滤掉无用的参数
          const { appName, appid, createByNameArr, ...restParams } = formData;
          let res = await saveOrderAssetDetail(restParams);
          if (res.code == 200) {
            this.$message.success(res.description);
            this.updateListData();
            // this.$utils.addOperateLog(res.data, `新建了标准`);
            let obj = {
              id: res.data,
              pageType: "detail",
            };
            this.$router.push({
              query: obj,
            });
          } else {
            throw new Error(`saveOrderAssetDetail func exec Error`);
          }
        }
        // }
      } catch (error) {
        throw new Error(`saveDetails func throw Error, Error Reason:`, error);
      }
    },
    // 更新
    async updateDetail() {
      try {
        let formData = await this.$refs.basicForm.getFormData();
        const { appName, appid, createByNameArr, ...restParams } = formData;
        const reqParams = {id: this.formData.id, ...restParams}
        let res = await updateOrderAssetDetail(reqParams);
        if (res.code == 200) {
          this.$message.success(res.description);
          this.updateListData();
          // this.$utils.addOperateLog(res.data, `新建了标准`);
          let obj = {
            id: this.formData.id,
            pageType: "detail",
            // 相同的query参数导致页面复用，用一个随机数区分开
            cache: Math.round(Math.random()*100000)
          };
          this.$router.push({
            query: obj,
          });
        } else {
          throw new Error(`saveOrderAssetDetail func exec Error`);
        }
      } catch (error) {
        throw new Error(`updateDetail func throw Error, Error Reason:`, error);
      }
    },
    // 删除
    deleteDetail() {
      this.$confirm("确定要删除选中数据吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteOrderAssetDetail({ id: this.formData.id }).then((res) => {
            if (res.code === 200) {
              this.$message.success(res.description);
              this.$utils.addOperateLog(this.formData.id, `删除了巡视标准`);
              this.updateListData();
              this.$refs.editPage.closePage();
            }
          });
        })
        .catch((e) => {
          console.error("deleteDetail函数执行删除失败", e);
        });
    },
    /* 更新列表页的数据 */
    updateListData() {
      /* 通过localStorage来实现浏览器不同窗口之间的通信 */
      let num = Math.floor(Math.random() * 1000) + 1; //产生随机数，保证每次的值都不一样
      localStorage.setItem("update", num); //设置localStorage里面的值，保证每次都会触发storage事件
    },
  },
  created() {
    this.init();
  },
};
</script>

<style lang="less" scoped>
.detailWrapper {
  background-color: #ffffff;
  .TitleImg {
    margin-right: 2px;
    font-size: 22px;
  }
  .plan-title {
    height: 40px;
    margin: 0 0 10px 0;
    .name {
      font-size: 18px;
      padding: 0 10px;
      height: 40px;
      font-weight: bold;
      line-height: 40px;
      text-align: left;
      padding: 0 10px;
    }
    .name-input {
      width: 400px;
      height: 40px;
      line-height: 40px;
    }
  }
}
</style>
